using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Principal;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.Security;
using Curriculum.Modelo.Clases;	
using Curriculum.Services;
using Microsoft.VisualBasic;
using Sharpen;

namespace ConcursoCV.UI.WebUserControls.Login
{
	/// <summary>
	/// Summary description for login1.
	/// </summary>
	public class Login : System.Web.UI.Page
	{
		protected System.Web.UI.WebControls.ValidationSummary vsLogin;
		protected System.Web.UI.WebControls.DropDownList ddlRol;
		protected System.Web.UI.WebControls.TextBox txtUsername;
		protected System.Web.UI.WebControls.RequiredFieldValidator rfvUsername;
		protected System.Web.UI.WebControls.TextBox txtPassword;
		protected System.Web.UI.WebControls.RequiredFieldValidator rfvPassword;
		protected System.Web.UI.WebControls.Label lblError;
		protected System.Web.UI.WebControls.Button btnAceptar;
	
		private string UserName
		{
			get { return this.txtUsername.Text; }
		}
		private string Password
		{
			get { return this.txtPassword.Text; }
		}
		private string Rol
		{
			get { return this.ddlRol.SelectedValue.ToString(); }
		}


		private void Page_Load(object sender, System.EventArgs e)
		{
			lblError.Text = string.Empty;
			if(!this.IsPostBack)
			{				
				//Cargo el combo
				PopulateCombo();				
			}	
		}

		private void PopulateCombo()
		{
			IList lista = Helper.SecurityHelper.GetRoles();
			Helper.ListHelper.FillDropDownList(this.ddlRol, "", "", lista, false);
		}

		private bool ValidarUsuario()
		{							
			Usuario usuario = BuscarUsuario();						

			//Si existe el usuario
			return (usuario != null);
		}

		private Usuario BuscarUsuario()
		{
			Usuario usuario = null;
			
//			if (Rol.Equals(typeof(RolGenerico).Name))
//			{
//				usuario = Usuario.GetGenerico();
//			}
//			else
//			{
				UsuarioService serv = new UsuarioService();
				usuario = serv.GetUsuario(Rol , UserName, Password);	
//			}
			
			return usuario;
		}

		private void LoginMethod( ) 
		{
			GenericPrincipal principal = null;
			GenericIdentity identity = null;

			if (ValidarUsuario())
			{
				identity = new GenericIdentity( UserName );
				principal = new GenericPrincipal( identity, new string[]{ Rol });

				//FormsAuthentication.RedirectFromLoginPage(this.txtUsername.Text, true);
			}
			else
			{
				identity = new GenericIdentity( string.Empty );
				principal = new GenericPrincipal( identity, new string[]{ string.Empty });				
				//Response.Redirect("login.ascx");
			}
			HttpContext.Current.User = principal;
		}

		private void RedirectFromLogin()
		{
		    // serialize the Principal into a String value
			string principalText = string.Empty;
			MemoryStream buffer = new MemoryStream();
			BinaryFormatter formatter = new BinaryFormatter();
			formatter.Serialize( buffer, HttpContext.Current.User );
			buffer.Position = 0;
			principalText = Convert.ToBase64String(buffer.GetBuffer());
			
			// create the ticket
			FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, 
												HttpContext.Current.User.Identity.Name,
												DateTime.Now,
												DateTime.Now.AddHours(1),
												false,
												principalText);


			// Encrypt the ticket.
			string encTicket = FormsAuthentication.Encrypt(ticket);
	
			// Create the cookie.
			Response.Cookies.Add( new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));

			// Redirect back to original URL.
			Response.Redirect( FormsAuthentication.GetRedirectUrl(txtUsername.Text, false));
		}


		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
			this.btnAceptar.Click += new System.EventHandler(this.btnAceptar_Click);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		
		private void btnAceptar_Click(object sender, System.EventArgs e)
		{
			LoginMethod();
			if ( HttpContext.Current.User.Identity.IsAuthenticated ) 
				RedirectFromLogin();
			else
				lblError.Text = "Verifique el usuario y password";
		}
	}
}
